<template>
  <base-breadcrumb :title="titleName">
    <a-card :bordered="false" style="over-flow:scroll">
      <title-name title="设计需求申请"></title-name>
      <a-form-model ref="ruleForm" :model="form" :rules="rules"
                    :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                    :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
        <a-row>
          <a-col :md="8" :sm="8">
            <a-form-model-item
                    label="设计需求类型" prop="designDemandTypeId" >
                <BaseInput v-model="form.designDemandType"  disabled placeholder="请输入" />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item
                    label="设计需求名称" prop="designDemandName" >
              <BaseInput disabled  v-model="form.designDemandName" placeholder="请输入"  />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item
                    :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
                    :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }"
                    label="期望回复时间" prop="expectRecoveryTime" >
              <BaseInput disabled  v-model="form.expectRecoveryTime" placeholder="请输入"  />
            </a-form-model-item>
          </a-col>

          <!-- 项目部 -->
          <a-col :md="8" :sm="8"  >
            <a-form-model-item label="单位名称"
                          :labelCol="{lg: {span: 6}, sm: {span:6}}"
                          :wrapperCol="{lg: {span: 18}, sm: {span: 18} }" prop="branchId">
              <BaseInput disabled  placeholder="请选择" v-model="form.branchName"></BaseInput>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8"   v-if="form.projectId">
            <a-form-model-item label="项目名称"
                          :labelCol="{lg: {span: 6}, sm: {span:6}}"
                          :wrapperCol="{lg: {span: 18}, sm: {span: 18} }" prop="projectId">
              <BaseInput disabled  placeholder="请选择" v-model="form.projectName"  ></BaseInput>
            </a-form-model-item>
          </a-col>

          <a-col :md="8" :sm="8"   v-if="form.projectId">
            <a-form-model-item
                    label="项目编号" prop="projectNum" >
              <BaseInput v-model="form.projectNum" disabled></BaseInput>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8"  v-if="form.projectId">
            <a-form-model-item
                    label="项目设计管理类别" prop="designType" >
              <BaseInput v-model="form.designType" disabled></BaseInput>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8" >
            <a-form-model-item
                    label="提出部门" prop="proposeDeptId" >
               <BaseInput v-model="form.proposeDept"  disabled  placeholder="请输入"  />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8" >
            <a-form-model-item
                    label="提出人" prop="proposePersonId" >
               <BaseInput v-model="form.proposePersonName"  disabled ></BaseInput>
            </a-form-model-item>
          </a-col>

        <!-- 公司-分公司 -->

          <a-col :md="8" :sm="8">
            <a-form-model-item
                    label="创建人" >
              <BaseInput v-model="form.creatorName" disabled></BaseInput>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item
                    label="创建时间" >
              <BaseInput v-model="form.createTime" disabled></BaseInput>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="24" :sm="24">
            <a-form-model-item  label="需求概述" prop="information" >
              <editor-bar  disabled  v-model="form.information" :isClear="isClear"></editor-bar>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
  
      <title-name title="上传相关附件"></title-name>
      <div>
        <a-row>
          <a-col :md="24" :sm="19">
            <div class="table-operator">
            <!-- <u-table
                    :listUrl="listUrl"
                    :uploadList="uploadList"
                    :deleteUrl="deleteUrl"
                    :businessId="businessId"
                    :reqMethod="reqMethod"
                    businessCode="PM24"></u-table> -->
          <u-table
            :isShow = 'false'
            :uploadArrys="uploadArrys"
            businessCode="PM24"
            :listUrl="listUrl"
            :uploadList="uploadList"
            :businessId="businessId"
            :deleteUrl="deleteUrl"
            @fileArrysData="fileArrysDatas"></u-table>
            </div>
          </a-col>
        </a-row>
      </div>
    </a-card>
    <a-card >
      <title-name title="设计支持报告上传"></title-name>
      <a-upload  name="file" :showUploadList='false' :before-upload="beforeUpload" @change="handleChanges">
        <a-button type="primary" style="margin-bottom: 20px;"><a-icon type="upload"  style="font-size: 1.2rem" />上传</a-button>
      </a-upload>
      <a-button type="" style="margin-bottom: 20px;margin-left: 20px" @click="deleteExteriorFile()"><a-icon   style="font-size: 1.2rem" />删除</a-button>

      <a-table bordered :columns="columnAssment" :data-source="dataAssement" :row-selection="rowSelection">
        <span slot="serial"  slot-scope="text, record, index">{{ index + 1 }}</span><span slot="action"  slot-scope="text, record, index">
            <a :href="'/api/ycloud-file-center/oper/download?access_token='+token+'&fileId='+record.fileId" target="_parent">导出</a>
        </span>
      </a-table>
    </a-card>

    <div class="footer page-btn-right-top">
      <a-button type="primary" :loading="loading"  @click="saveSubmit()">提交</a-button>
      <a-button type="default"  @click="goBack">关闭</a-button>
    </div>
  </base-breadcrumb>
</template>

<script>
  import Vue from 'vue'
  import { STable, Ellipsis } from '@/components'
  import EditorBar from '@/components/Editor/editor'
  import {addBasic ,getProjectType} from '@/api/design/plotsPlan'
  import { getScoreList  ,addScoreList, editScoreList} from '@/api/evaluate'
  import { addDemandList,getDetails ,editDemandList } from '@/api/design/demand'
  import  { getTypes,getOrgUsers ,getOrganizePeopleList ,getDept} from '@/api/commons'
  import { themeChoose } from '@/mixin/mixin'
  import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
  import SelectProject from '@/components/Select/SelectProject' // 项目
  import { getProjectsDel} from '@/api/project/projects'

  import { getDesignDetails, editDesignChange,deleteDesignReportFile,designSupportSubmit } from '@/api/project/designChange'
  import { uploadFile,deleteUploadFile } from '@/api'
  import { completeTask } from '@/api/process'

  const columnAssment = [
    {
      title: '序号',
      dataIndex: 'serial',
      width: '5%',
      scopedSlots: { customRender: 'serial' },
    },
    {
      title: '附件名称',
      dataIndex: 'fileName',
      width: '35%',
    },
    {
      title: '附件格式',
      dataIndex: 'suffixName',
      width: '35%',
    },
    {
      title: '操作',
      key: 'action',
      width: '20%',
      scopedSlots: { customRender: 'action' },
    },
  ];
  export default {
    name:'a'+ Date.now(),
    mixins:[themeChoose],
    components:{
      STable,
      EditorBar,
      SelectSubCompany,
      SelectProject
    },
    data(){
      return{
        loading:false,
        columnAssment,
        dataAssement:[],
        uploadFile:{},
        deleteObj:{},

        fileFileds:null,
        fileIds:[],

        selectedRowKeys: [],
        selectedRows: [],
        selectId:[],

        titleName:'',
        dataSource:[],
        fileArrysDatas:[],
        forms:{},
        projectManagers:[],

        // 查询参数
        queryParam: {},


        type:'',
        confirmLoading:false,
        columns:'',
        id:'',
        // 附件上传
        listUrl:'',
        deleteUrl:'',
        uploadArrys:[],
        uploadList:' ',
        proposeDept:{},
        memberList:[],
        businessId:' ',
        businessCode:'PM24',
        reqMethod:'post',
        name:'',
        typeList:[],
        deptList:[],
        deptId:'',
        proposePerson:{},
        designType:[],
        test:'',  
        isClear: false,
        information:"" ,
        editorContent: '',
        status:'',
        projectLevel:false,//是否为项目部层级
        branchLevel:false,//是否为分公司层级
        companyLevel:false,//是否为公司层级
        pageType:'',
        jobsList:[],
        userId:'',
        branchName:'',
        user:'',
        disabled:false,
        form:{
          createTime:this.getNowTime(),
          creatorName:''
        },
        visible:false,
        rules: {},
        procInstId: '', //当前流程实例ID
        taskId: '', //当前流程节点ID
        processName: '', //流程名称
        taskName: '', //当前流程节点名称
        taskDefKey: '', //任务标识
        currentTime: '', //当前审批时间
        currentUser: '', //当前审批人
        token:''
      }
    },
    computed: {
      rowSelection() {
        return {
          selectedRowKeys: this.selectedRowKeys,
          selectedRows: this.selectedRows,   // 当前行所有数据
          onChange: this.onSelectChanges
        }
      }
    },
    created() {
      const {
        type,
        code,
        level,
        btype,
        businessId,
        procInstId,
        name,
        processName,
        detailUrl,
        taskId,
        taskDefKey,
      } = this.$route.query

      this.id = this.$route.query.businessId
      this.getDetails()
      if (!this.id) {
        this.$error({ content: '无指定业务ID，将自动关闭' })
        setTimeout(() => {
          window.close()
        }, 1500)
        return
      }
      this.procInstId = procInstId
      this.taskName = decodeURIComponent(name)
      this.processName = decodeURIComponent(processName)
      document.title = this.processName + '-' + this.taskName
      if (detailUrl) {
        this.detailUrl = decodeURIComponent(detailUrl)
      }
      this.taskId = taskId
      this.taskDefKey = taskDefKey
      // this.currentTime = moment().format('yyyy-MM-DD HH:mm')
      this.currentUser = Vue.getAcloudProvider().getUserInfo()

      this.userId = JSON.parse(sessionStorage.getItem('ycloud-user_info')).id
      this.form.creatorName = JSON.parse(sessionStorage.getItem('ycloud-user_info')).employee.name
      this.id = this.$route.query.id
      this.businessId = this.$route.query.id
      this.status = this.$route.query.status
      this.type = this.$route.query.type

      this.token = Vue.getAcloudProvider().getAccessToken()

    },

    methods:{
      deleteExteriorFile(){

        let that = this;
        if(that.selectedRowKeys.length == 0){
          that.$message.error("请先选中需要删除的附件！")
          return;
        }
        if(that.id){
          that.$confirm({
            title: '删除',
            content: '确定删除附件吗？',
            onOk() {
              let data = that.dataAssement
              let selectDatas = that.fileIds
              that.dataAssement = data.filter((item) => {
                return !selectDatas.includes(item.commonId)
              })


              let commonIds = []
              that.dataAssement.forEach && that.dataAssement.forEach((item)=>{
                commonIds.push(item.commonId)
              })


              that.form.reportFileIds = commonIds
              that.selectedRowKeys = []
              that.selectedRows = []
              that.$message.success("删除附件成功！")
            },
            onCancel() {},
          });

        }else{
          that.$confirm({
            title: '删除',
            content: '确定删除附件吗？',
            onOk() {
              deleteUploadFile({fileIds:that.fileFileds}).then(res=>{
                if(res.code == '0' || res.data.code == '0'){
                  let data = that.dataAssement
                  let selectDatas = that.fileIds
                  that.dataAssement =  data.filter(item => { return !selectDatas.includes(item.id); });
                  that.selectedRowKeys = []
                  that.selectedRows = []
                  that.$message.success("删除附件成功！")
                }
              })
            },
            onCancel() {},
          });

        }

      },

      onSelectChanges(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
        let fileFileds = []
        let fileIds = []
        selectedRows.forEach(function(obj,i) {
          fileFileds.push(obj.fileId)
          fileIds.push(obj.commonId)
        })
        this.fileFileds = fileFileds.join(',')   // 删除公共附件
        this.fileIds = fileIds                   // 有业务id 删除附件

      },
      // 上传

      beforeUpload(info){
        this.uploadFile = info
        return false
      },

      handleChanges(info) {
        let that = this
        const data = new FormData()
        data.append("file",that.uploadFile)
        data.append("businessCode",that.businessCode)

        let arr = []
        uploadFile( data ).then(res => {
          if(res.code === 200 ){
            arr.push(res.data)
            if (that.dataAssement == null) {
              that.dataAssement = arr
            } else {
              that.dataAssement = that.dataAssement.concat(arr)
            }

            let commonIds = []
            that.dataAssement.forEach && that.dataAssement.forEach((item)=>{
              commonIds.push(item.commonId)
            })

            that.form.reportFileIds = commonIds
          }
        })
      },


      handelUnApproval(){  // 审批不通过
        this.$confirm({
          title: '警告提醒！',
          content: '确定审批不通过？',
          okType: 'danger',
          onOk() {

          },
          onCancel() {

          },
        });
      },

      handelApproval(){    // 审批通过  判断(支持人员必填)
        this.$confirm({
          title: '警告提醒！',
          content: '确定审批通过？',
          okType: 'danger',
          onOk() {

          },
          onCancel() {
          },
        });
      },


      getDetails(){
        if(this.id){
          console.log("审批设计支持需求界面")
          getDetails({id:this.id}).then(res=>{
            this.form = res.data
            this.uploadArrys = res.data.designFileIdsInfo
            // getOrganizePeopleList({id:this.form.projectId}).then(res=>{
            //   this.memberList = res.data
            // })
          })
          getDept({id:this.form.projectDeptOrgId}).then(res=>{
            this.deptList = res.data
          })
        }
      },

      notifyParent() {
        window.opener.postMessage('finish', window.location.origin)
      },
      taskFinish() {
        const data = {
          procInstId: this.procInstId,
          taskId: this.taskId,
          userId: this.currentUser.id,
          formData: {
            reject:false,
            opinions: ''
          },
        }

        return completeTask(data)
          .then((res) => {
            if (res.status === 200) {
              this.notifyParent() // 通知父窗口
              // this.$success({
              //   content: '提交成功，即将自动关闭当前窗口',
              //   onOk() {
                  window.close()
              //   },
              // })
              // setTimeout(() => {
              //   window.close()
              // }, 2000)
            } else {
              this.$error({ content: '提交失败，请稍后重试' })
            }
            return res
          })
          .catch((err) => {
            return err
          })
      },
      saveSubmit(){
        let that = this;
        let arr = []
        let arrysData = that.dataAssement
        if(arrysData.length>0){
          arrysData.forEach(function(obj,i) {
            arr.push(obj.commonId)
          })
        }

        if(arr.length == 0){
          that.$message.error("请先上传设计支持报告附件！")
          return;
        }
        that.loading = true
        designSupportSubmit({reportFileIds:arr,id:that.id}).then(res=>{
          that.loading = false
          if(res.code == 200 || res.data.code == 200){

            that.$message.success("提交成功！")
            that.taskFinish()
          }
        }).catch(() => {
          that.loading = false
        })
      },
      goBack(){ 
        window.close()
      },



    }
  }
</script>

<style scoped>
  .input{
    width:100%
  }  
  .footer{
    float:right;
    margin-right:10px
  }
  .footer button{
    margin-left:10px
  }
</style>
